<?php
namespace App\Http\Controllers\Api\Repositories;

use App\Models\Posts\WxCollect as Model;
use App\Models\Posts\WxPost;
use App\Models\WxNotice;
use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WxCollectRepositores
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /**
     * 点赞
     */
    public static function collect($uid, $posts_id)
    {
        DB::beginTransaction();

        try {
            $posts_user_id = WxPost::where('id', $posts_id)->pluck('user_id')->first();
            $isExists = Model::where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->exists();
            if (!$isExists) {
                // 收藏
                $wxLike = new Model();
                $wxLike->posts_user_id = $posts_user_id;
                $wxLike->posts_id = $posts_id;
                $wxLike->user_id = $uid;
                $wxLike->save();

                if($uid != $posts_user_id){
                    $user = UserUtils::get_cached_user($uid);
                    UserUtils::add_user_notice(2006, $posts_user_id, '收到了一个收藏', '您的笔记被「' . '<a href="/pages/user/user?id='.$user['id'].'">'.$user['user_name'].'</a>' . '」收藏啦！', 101, $posts_id);
                }
            }
            Redis::sadd('realtime:post:set', $posts_id);
            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }

    }

    public static function uncollect($uid, $posts_id)
    {
        DB::beginTransaction();
        try {
            $posts_user_id = WxPost::where('id', $posts_id)->pluck('user_id')->first();
            // 取消收藏
            (new Model())->where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->delete();


            (new WxNotice())->where('posts_id', $posts_id)
                ->where('user_id', $posts_user_id)
                ->where('notice_type', 3)
                ->delete();
            Redis::sadd('realtime:post:set', $posts_id);
            DB::commit();
            return true;

        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

}
